//
//  BlueToothManager.m
//  zhongdaodianziApp
//
//  Created by chinadfwx on 2018/9/15.
//  Copyright © 2018年 zhongDaoDianZi. All rights reserved.
//

#import "BlueToothManager.h"

#define scan_max_second 5

@interface BlueToothManager()<CBPeripheralDelegate,CBCentralManagerDelegate>
//@property (nonatomic, strong) ZDBlueListView *blueView;
@property (nonatomic, strong) NSMutableArray *currentMusicNameArray;
@property (nonatomic, strong) NSMutableString *currentMusicString;
@end

@implementation BlueToothManager
+ (instancetype)shareInstance {
    static BlueToothManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
        [manager initWithStart];
    });
    return manager;
}
-(void)initWithStart{
    self.centerManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
}

-(void)centerManagerScanDevice{
    [self.centerManager scanForPeripheralsWithServices:nil options:nil];
    if (self.delegate && [self.delegate respondsToSelector:@selector(BlueToothManagerScanDevice)]) {
        [self.delegate BlueToothManagerScanDevice];
    }
}

-(void)centerManagerCancleScanDevice{
    [self.centerManager stopScan];
    if (self.delegate && [self.delegate respondsToSelector:@selector(BlueToothManagerCancleScanDevice)]) {
        [self.delegate BlueToothManagerCancleScanDevice];
    }
}


#pragma mark - 蓝牙列表显示
#pragma mark - 显示提示信息
-(void)alertViewTipsShow:(NSString *)message{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil]];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertVC animated:YES completion:nil];
}
#pragma mark - CBCenteralManagerDelegate
-(void)centralManagerDidUpdateState:(CBCentralManager *)central{
    switch (central.state) {
        case CBManagerStateUnknown:{
            [self alertViewTipsShow:@"请确保手机蓝牙已经打开"];
        }
            break;
        case CBManagerStatePoweredOn:{
            [self centerManagerScanDevice];
//            [self.centerManager scanForPeripheralsWithServices:nil options:nil];
        }
            break;
        case CBManagerStateResetting:{
            [self alertViewTipsShow:@"The connection with the system service was momentarily lost, update imminent."];
        }
            break;
        case CBManagerStatePoweredOff:{
            [self alertViewTipsShow:@"蓝牙处于关闭状态，请将蓝牙开启"];
        }
            break;
        case CBManagerStateUnsupported:{
            [self alertViewTipsShow:@"蓝牙不支持"];
        }
            break;
        case CBManagerStateUnauthorized:{
            [self alertViewTipsShow:@"无法认证蓝牙"];
        }
            break;
        default:
            break;
    }
}
#pragma mark - 搜索发现周边蓝牙
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI{
    if (![self.peripheralArray containsObject:peripheral] && peripheral.name.length > 0) {
        NSLog(@"%@",peripheral);
        [self.peripheralArray addObject:peripheral];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"BluetoothDiscoverPeripheral" object:nil];

    }
//    if (peripheral.name.length > 0) {
//        NSLog(@"%@",peripheral);

//    }
    // HT CAR BT 4.0
//    if ([peripheral.name isEqualToString:@"HT CAR BT BLE"]) {
//        self.peripheral = peripheral;
//        [self.centerManager connectPeripheral:self.peripheral options:nil];
//
//        [self centerManagerCancleScanDevice];
//
//    }
    
}

#pragma mark - 蓝牙连接回调
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    NSLog(@"%@蓝牙连接成功",peripheral.name);
    peripheral.delegate = self;
    self.peripheral = peripheral;
    [self centerManagerCancleScanDevice];
    [peripheral discoverServices:nil];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"BluetoothConnectPeripheralSuccess" object:nil];
    if (self.delegate && [self.delegate respondsToSelector:@selector(blueToothManagerConnectedCentral:DidConnectedPeripheral:)]) {
        [self.delegate blueToothManagerConnectedCentral:central DidConnectedPeripheral:peripheral];
    }
}
#pragma mark - 蓝牙断开回调
-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    NSLog(@"%@蓝牙断开",peripheral.name);
    [[NSNotificationCenter defaultCenter]postNotificationName:@"BluetoothDisConnectPeripheralSuccess" object:nil];

//    [self.centerManager connectPeripheral:peripheral options:nil];
//    if (self.delegate && [self.delegate respondsToSelector:@selector(blueToothManagerDisConnectedCentral:peripheral:error:)]) {
//        [self.delegate blueToothManagerDisConnectedCentral:central peripheral:peripheral error:error];
//    }
}
#pragma mark - 发现服务
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    for (CBService *s in peripheral.services) {
        NSLog(@"%@",[s.UUID UUIDString]);
        if ([s.UUID.UUIDString isEqualToString:@"FFF0"]) {
            [peripheral discoverCharacteristics:nil forService:s];
        }
        
    }
}

-(void)savePassword:(NSString *)password peripheralName:(NSString *)peripheralName{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray *array = [NSMutableArray array];
    NSArray *oldArray = [self getUserDefaultDeviceAndPasswordArray];
    [array addObjectsFromArray:[self getUserDefaultDeviceAndPasswordArray]];
    BOOL result = NO;
    for (NSDictionary *dict in oldArray) {
        if ([dict[@"name"] isEqualToString:peripheralName]) {
            result = YES;
            if ([array containsObject:dict]) {
                [array removeObject:dict];
                [array addObject:@{@"name":peripheralName,@"password":password}];
            }
        }
    }
    if (result == NO) {
        [array addObject:@{@"name":peripheralName,@"password":password}];
    }
    [userDefaults removeObjectForKey:PASSWORD_KEY];
    [userDefaults setObject:array forKey:PASSWORD_KEY];
    [userDefaults synchronize];
}

-(NSArray *)getUserDefaultDeviceAndPasswordArray{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    return [userDefaults objectForKey:PASSWORD_KEY];
}

-(NSString *)getUserDefaultPassword:(NSString *)peripheralName{
    NSArray *array = [self getUserDefaultDeviceAndPasswordArray];
    NSDictionary *dict;
    for (NSDictionary *dic in array) {
        if ([dic[@"name"] isEqualToString:peripheralName]) {
            dict = dic;
        }
    }
    if (dict.count > 0) {
        return dict[@"password"];
    }
    return @"";
}

-(BOOL)judePasswordWithKey:(NSString *)peripheralName{
    NSString *string = [self getUserDefaultPassword:peripheralName];
    if (string.length > 0) {
        return YES;
    }
    return NO;
}


#pragma mark - 发现服务特征
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    for (CBCharacteristic *cha in service.characteristics) {
        NSLog(@"%s, didDiscoverCharacteristicsForService = %d, char = %@", __FUNCTION__, __LINE__, cha);
        
        if ([cha.UUID.UUIDString isEqualToString:@"FFF1"]) {
            self.characteristic = cha;
            [peripheral setNotifyValue:YES forCharacteristic:cha];
            NSString *savePwd = [self getUserDefaultPassword:peripheral.name];
            if (savePwd.length > 0 ) {
                self.password = savePwd;
                NSMutableString *sixteenPassword = [NSMutableString string];
                [sixteenPassword appendString:@"0701"];
                
                for (NSInteger i = 0; i < savePwd.length; i ++) {
                    NSString *singer = [savePwd subStringWithRangeForNil:NSMakeRange(i, 1)];
                    [sixteenPassword appendString:[CalculateTool getHexByDecimal:singer.integerValue]];
                    
                }
                [self sendDataWithCommand:sixteenPassword];
            }else{
                if (self.password.length > 0) {
                    NSMutableString *sixteenPassword = [NSMutableString string];
                    [sixteenPassword appendString:@"0701"];
                    
                    for (NSInteger i = 0; i < self.password.length; i ++) {
                        NSString *singer = [self.password subStringWithRangeForNil:NSMakeRange(i, 1)];
                        [sixteenPassword appendString:[CalculateTool getHexByDecimal:singer.integerValue]];
                        
                    }
                    [self sendDataWithCommand:sixteenPassword];
                }
                
                [[NSNotificationCenter defaultCenter]postNotificationName:@"textAlertViewShowNotification" object:nil];
                
            }
            
        }
    }
    
}


#pragma mark - 读取特征返回信息
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    NSData * data = characteristic.value;
    NSString *dataString = [CalculateTool convertDataToHexStr:data];
    if ([characteristic.UUID.UUIDString isEqualToString:@"FFF1"]) {
        if (dataString.length < 40) {
            NSMutableString *temString = [NSMutableString string];
            for (NSInteger i = dataString.length; i < 40; i++) {
                [temString appendFormat:@"0"];
            }
            dataString = [NSString stringWithFormat:@"%@%@",dataString,temString];
        }
        [[NSNotificationCenter defaultCenter]postNotificationName:@"dataReceiveNotification" object:dataString];

        NSLog(@"%@",dataString);
    }
    

//#warning 这里开始做处理
    
    
    
    
}

#pragma mark - 转换歌词
-(NSString *)deleteAllZeroFromString:(NSString *)string{
    NSInteger location = 0;
    for (NSInteger i = 0; i <string.length; i++) {
        NSString *s = [string subStringWithRangeForNil:NSMakeRange(i, 1)];
        if (i != string.length-1 && [s isEqualToString:@"0"] ) {
            NSString *s1 = [string subStringWithRangeForNil:NSMakeRange(i+1, 1)];
            if ([s isEqualToString:s1]) {
                if (i != 0) {
                    NSString *s2 = [string subStringWithRangeForNil:NSMakeRange(i-1, 1)];
                    if (![s2 isEqualToString:s]) {
                        location = i;
                    }
                }
            }
            
        }
        
    }
    NSLog(@"去0后%@",[string substringToIndex:location]);
    return [string substringToIndex:location];
}

- (NSString *)stringFromHexString:(NSString *)string {
    NSString*command = string;
    NSInteger yu = command.length %4;
    if (yu % 4 > 0) {
        for (NSInteger i = 0; i < 4 - yu; i ++) {
            command = [NSString stringWithFormat:@"%@0",command];
        }
    }
    //1位倒转
    NSMutableString *tempComandString = [[NSMutableString alloc]init];
    for (NSInteger i = 0; i < command.length; i = i+2) {
        NSString *subString = [command subStringWithRangeForNil:NSMakeRange(i, 2)];
        NSMutableString *newString = [[NSMutableString alloc]init];
        for (NSInteger i = subString.length - 1; i >= 0; i --) {
            [newString appendString:[subString subStringWithRangeForNil:NSMakeRange(i, 1)]];
        }
        [tempComandString appendString:newString];
    }
    command = [NSString stringWithFormat:@"%@",tempComandString];
    //每两位倒转
    NSMutableString *mewTempString = [NSMutableString string];
    for (NSInteger i = 0; i < command.length; i = i+4) {
        NSString *subString = [command subStringWithRangeForNil:NSMakeRange(i, 4)];
        NSMutableString *newString = [[NSMutableString alloc]init];
        for (NSInteger i = subString.length - 1; i >= 0; i --) {
            [newString appendString:[subString subStringWithRangeForNil:NSMakeRange(i, 1)]];
        }
        [mewTempString appendString:newString];
    }
    command = [NSString stringWithFormat:@"%@",mewTempString];
    command =[command stringByReplacingOccurrencesOfString:@" "withString:@""];
    
    NSMutableData *commandToSend= [[NSMutableData alloc] init];
    
    unsigned char whole_byte;
    
    char byte_chars[3] = {'\0','\0','\0'};
    
    int i;
    
    for (i=0; i< [command length]/2; i++) {
        
        byte_chars[0] = [command characterAtIndex:i*2];
        
        byte_chars[1] = [command characterAtIndex:i*2+1];
        
        whole_byte= strtol(byte_chars, NULL, 16);
        [commandToSend appendBytes:&whole_byte length:1];
    }
    NSLog(@"commandToSend:%@",commandToSend);
    
    NSString *string11 = [[NSString alloc]initWithData:commandToSend encoding:NSUnicodeStringEncoding];
//    [ProjectManager shareInstance].current_sd_or_usb_music = string11;
//    [self.horseLampContentView setHorseLabelStringWith:[NSString stringWithFormat:@"%@. %@",self.label_number_of_play_music.text,string11]];
    //    self.label_show_play_message.text = [NSString stringWithFormat:@"%@. %@",self.label_number_of_play_music.text,string11];
    //    [self linearAnimation];
//    NSLog(@"newString:%@",[ProjectManager shareInstance].current_sd_or_usb_music);
    return string11;
}
#pragma mark - 蓝牙列表ViewDelegate
-(void)sendDataWithCommand:(NSString *)command{
    if (self.peripheral != nil && self.peripheral.state == CBPeripheralStateConnected) {
        [[BlueToothManager shareInstance].peripheral writeValue:[CalculateTool convertHexStrToMutableData:command] forCharacteristic:[BlueToothManager shareInstance].characteristic type:CBCharacteristicWriteWithResponse];
    }else
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先确认周边蓝牙设备,并连接" preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertVC animated:YES completion:nil];
        
    }
}

-(void)sendDataWithCommandWithOutResponse:(NSString *)command{
    if (self.peripheral != nil && self.peripheral.state == CBPeripheralStateConnected) {
        [[BlueToothManager shareInstance].peripheral writeValue:[CalculateTool convertHexStrToMutableData:command] forCharacteristic:[BlueToothManager shareInstance].characteristic type:CBCharacteristicWriteWithoutResponse];
    }else
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先确认周边蓝牙设备,并连接" preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertVC animated:YES completion:nil];
        
    }
}

#pragma mark - timerHandleAction
-(void)timerHandleAction{
    
}
#pragma mark - 懒加载
-(NSMutableArray *)peripheralArray{
    if (!_peripheralArray) {
        _peripheralArray = [NSMutableArray array];
    }
    return _peripheralArray;
}

-(NSMutableArray *)currentMusicNameArray{
    if (!_currentMusicNameArray) {
        _currentMusicNameArray = [NSMutableArray array];
    }
    return _currentMusicNameArray;
}

-(NSMutableString *)currentMusicString{
    if (!_currentMusicString) {
        _currentMusicString = [NSMutableString string];
    }
    return _currentMusicString;
}


@end
